<template>
  <!-- 商品集合组件 -->
  <view class="items_grid_list">
    <block v-if="itemShowType == 'vertical'">
      <cmsproductList :listData.sync = "itemsData" :itemData.sync="itemsData.content"></cmsproductList>
    </block>

    <!--尺码选择器 开始-->
    <view v-if="showSizeList" class="topSizeList">
      <view class="bg" catchtouchmove="preventTouchMove"></view>
      <view class="sizeBox">
        <view class="cascade_header">
          <text class="quxiao" @click="cancelPicker">取消</text>
          <text class="queren" @click="onSizePick">确认</text>
        </view>
        <picker-view :value="defaultValue" indicator-style="height: 50px;" style="width: 100%; height: 300px;background-color: #fff;" @change="bindChange">
          <picker-view-column>
            <view>选择尺码</view>
            <view v-for="(item, index) in colorSizeList" :key="index">
              {{ item.skuProperties[1].valueName }}
              <text v-if="item.qty < 1">已售罄</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    <!--尺码选择器 结束-->

    <!--加购成功商品提示框开始-->
    <view v-if="addCartSuccess" class="topBox">
      <view class="iconfont icon-cuowu1" @click="closeMiniCart"></view>
      <view class="gContent">
        <view class="gImg"><image :src="skuImageUrl"></image></view>
        <view class="gInfo">
          <view class="gNmae">{{ itemName }}</view>
          <view>
            <view class="markPrice" v-if="markingPrice / 1 > price / 1">
              <view class="linePrice">{{ '¥ ' + markingPrice / 1 }}</view>
              <view class="nowPrice">{{ '¥ ' + price / 1 }}</view>
            </view>
            <view v-else>
              <view class="price">{{ '¥ ' + price / 1 }}</view>
            </view>
          </view>
          <view class="markPrice rule-price-box" v-if="item.rulesArr.length > 0">
            <block v-for="(innerItem, innerIndex) in item.rulesArr" :key="innerIndex">
              <view class="rule-price goodsTag">{{ innerItem.priceTag}} {{ '¥ ' + innerItem.strategyPrice}}</view>
            </block>
          </view>
          <view class="gColor">颜色 {{ colorName }}</view>
          <view>尺码 {{ sizeName }}</view>
        </view>
      </view>
      <!-- <view class="iconfont icon-bag-o" @click="goShoppingCart">成功加入购物车</view> -->
    </view>
    <!--加购成功商品提示框结束-->
  </view>
</template>

<script module="filterChecked" lang="wxs" src="../../../utils/filter.wxs"></script>
<script>
import Vue from 'vue';
import api from '@/api/api';
import tip from '@/utils/tip';
import util from '@/utils/util';
import customize from '@/utils/customize';
import { SEL_CLASS_CODE, SEL_ACTIVE_CODE, SYSTEM_INFO, CUSTOMER_INFO, CART_KEY, MERCHANT_INFO, USER_INFO, USER_SPECICAL_INFO } from '@/utils/constant';
import cmsproductList from './productList';
export default {
  // #ifdef APP-PLUS | H5
  name: 'wxParseTemplateItemsType',
  // #endif
  // #ifdef MP
  name: 'wxParseTemplate0ItemsType',
  // #endif
  props: {
    itemsData: Object,
    isAppend: Number,
    userLogin: Boolean,
    favoriteItemIds: {
      type: Array,
      twoWay: true
    },

    addfavorites: String
  },

  components:{
    cmsproductList,
  },

  data() {
    return {
      itemShowType: 'vertical',
      showNoStock: 0, //默认不显示0库存
      isValid: 1, //默认不显示0库存
      modeStyle: 'widthFix',

      frontCode: '',
      itemId: '',
      valueId: '',

      favoritesList: [],
      // favoriteItemIds:[],
      childFavoriteItemIds: [],
      collectedItems: [],

      addCartSuccess: false,

      // 快速加购
      colorName: '',
      sizeName: '',
      skuImageUrl: '',
      productList: {},
      markingPrice: 0,
      price: 0,
      valueId: 0,
      detail: {},
      itemName: '',
      itemCode: '',

      colorSizeList: [],
      defaultValue: [0],
      showSizeList: false,
      addCartItemCode: '',
      addCartSkuCode: '',
      addCartSkuId: '',
      addCartQty: 1,
      cartKey: '',

      clickAttrArr: [], // 未登录状态点击收藏按钮
      clickType: ''
    };
  },

  created: function(option) {
    let that = this;
    if (this.isLogin) {
      that.childFavoriteItemIds = that.favoriteItemIds;
      let clickType = uni.getStorageSync('clickType') || '';
      if (clickType) {
        if (clickType.type == 'favorite') {
          that.appendFavorites(clickType.attrArr[0], clickType.attrArr[1], attrArr[2]);
        } else if (clickType.type == 'addCart') {
          that.quickPurchase(clickType.attrArr[1], clickType.attrArr[2]);
        }
        uni.removeStorageSync('clickType');
      }
    } else {
      uni.removeStorageSync('clickType');
    }
  },

  watch: {
    addfavorites: function(newVal, oldVal) {
      let that = this;
      this.addfavorites = newVal;
      // 查询商品是否已收藏,没有则调收藏接口
      this.inquireFavorites(that.itemId, that.valueId);
      this.$emit('pAppendFavorites');
    },
    favoriteItemIds: function(newVal, oldVal) {
      let that = this;
      that.childFavoriteItemIds = newVal;
    }
  },

  methods: {
    // 禁止屏幕滚动
    preventTouchMove: function() {},
    /**
     * 加入收藏
     * @param frontCode
     * @param itemId
     * @param valueId
     */
    addFavorites(frontCode, itemId, valueId) {
      let that = this;
      that.appendFavorites(frontCode, itemId, valueId);
    },

    // 取消收藏
    cancelFavorite(e) {
      let that = this;
      let favoriteId = e.currentTarget.dataset.value;
      let textArr = e.currentTarget.dataset.text;
      let itemArr = textArr.split('_');

      that.favoritesList[itemArr[0] - itemArr[1]] = '';
      that.delFavorite(favoriteId);
    },

    /**
     * @param {Object} e
     * 点击加入购物车授权
     */
    addcartGotUserInfoToRegister(e) {
      let that = this;
      that.clickType = 'addCart';
      that.onGotUserInfoToRegister(e);
    },

    /**
     * 授权 点击收藏
     * @param e
     */
    favGotUserInfoToRegister(e) {
      let that = this;
      that.clickType = 'favorite';
      that.onGotUserInfoToRegister(e);
    },

    /**
     * 快速购买
     */
    quickPurchase(itemId, valueId) {
      let that = this;
      that.valueId = valueId;
      that.getGoodsDetail(itemId);
    },

    //取消按钮
    cancelPicker() {
      //这里也是动画，然其高度变为0
      this.hidePicker();
    },
    //确认按钮
    onSizePick() {
      let that = this;
      //一样是动画，级联选择页消失，效果和取消一样
      that.hidePicker();
      that.addShoppingCart();
    },

    //滚动选择的时候触发事件
    bindChange(e) {
      //这里是获取picker-view内的picker-view-column 当前选择的是第几项
      let that = this;
      let e_value = e.detail.value;
      that.addCartItemCode = that.colorSizeList[e_value - 1].barcode;
      that.addCartSkuCode = that.colorSizeList[e_value - 1].skuCode;
      that.addCartSkuId = that.colorSizeList[e_value - 1].skuId;
      that.sizeName = that.colorSizeList[e_value - 1].skuProperties[1].valueName;
    },

    // 关闭
    closeMiniCart() {
      let that = this;
      that.addCartSuccess = false;
    },

    // 跳转到购物车页
    goShoppingCart() {
      let that = this;
      uni.navigateTo({
        url: '/pages/shopCart'
      });
    },

    /**
     * 获取用户收藏列表
     */
    getFavoriteList: async function() {
      let that = this;
      that.favoriteItemIds = [];
      if (uni.getStorageSync(CUSTOMER_INFO).customerId) {
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        //获取商户信息
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const memberFavoriteList = await api.getFavoritesItems({
          method: 'GET',
          header: { jwt: jwt },
          query: {
            merchant_id: merchantInfo.cloudMerchantId,
            page_no: 1,
            page_size: 20,
            store_id: merchantInfo.cloudMerchantStoreId
          }
        });

        if (memberFavoriteList.code === 1000 && memberFavoriteList.data.content.length > 0) {
          that.collectedItems = memberFavoriteList.data.content;
          that.collectedItems.forEach(item => {
            let tempFavorite = { itemId: item.itemId, valueId: item.valueId, favotite: item.favoritesId };
            that.favoriteItemIds.push(tempFavorite);
          });
        }
      }
    },

    // 新增商品收藏信息
    appendFavorites: async function(frontCode, itemId, valueId) {
      let that = this;
      that.favoritesList[itemId - valueId] = itemId;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      //获取商户信息
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      if (jwt) {
        const appendfavorite = await api.appendFavorites({
          method: 'POST',
          header: {
            jwt: jwt
          },
          query: {
            frontCode: frontCode,
            itemId: itemId,
            merchantId: merchantInfo.cloudMerchantId,
            storeId: merchantInfo.cloudMerchantStoreId,
            valueId: valueId
          }
        });
        if (appendfavorite.code == 1000) {
          that.$emit('pGetFavoriteList');
        } else {
          // tip.plainText('收藏失败');
        }
      }
    },

    // 删除商品收藏信息
    delFavorite: async function(favorites_id) {
      let that = this;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      const delfavorite = await api.delFavorites(
        {
          method: 'PUT',
          header: {
            jwt: jwt
          }
        },
        favorites_id
      );
      if (delfavorite.code == 1000) {
        that.$emit('pGetFavoriteList');
      } else {
      }
    },

    onGotUserInfoToRegister: async function(e) {
      let that = this;
	  let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo
	  const accountInfo = uni.getAccountInfoSync()

      try {
        if (e.detail.errMsg === 'getUserInfo:ok') {
          let productAttr = e.currentTarget.dataset.text; //0753256001_19034_41
          let attrArr = productAttr.split('_');
          that.clickAttrArr = productAttr.split('_');

          this.getMyBackground(uni.getStorageSync('merchantInfo').cloudMerchantId, uni.getStorageSync('merchantInfo').cloudMerchantStoreId);
          let res = await uni.login();
          uni.setStorageSync(USER_INFO, e.detail.userInfo);
          if (res[1].code) {
            let systemInfo = uni.getSystemInfoSync();
            uni.setStorageSync(SYSTEM_INFO, systemInfo);
            const rlt = await api.obtainUserOpenid({
              query: {
                app_id: accountInfo.miniProgram.appId,
                js_code: res[1].code
              }
            });
            if (rlt.code === 1000) {
              if (rlt.data.openid) {
                uni.setStorageSync(USER_SPECICAL_INFO, rlt.data);

                //获取商户信息
                let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
                if (merchantInfo.cloudMerchantId) {
                  //验证是否绑定已经存在用户
                  let customerInfo = await api.checkUser({
                    method: 'POST',
                    query: {
                      appId: accountInfo.miniProgram.appId,
                      merchantId: merchantInfo.cloudMerchantId,
                      openId: rlt.data.openid,
                      loginToken: rlt.data.loginToken || ''
                    }
                  });
                  // 没有注册
                  if (customerInfo.code !== 1000) {
                    uni.navigateTo({
                      url: '/pages/customer/register'
                    });

                    let clickType = {
                      type: that.clickType,
                      attrArr: that.clickAttrArr
                    };
                    uni.setStorageSync('clickType', clickType);
                  } else {
					  uni.setStorageSync(CUSTOMER_INFO, customerInfo.data);
                    getApp().globalData.customerInfo = customerInfo.data;
                    this.$emit('loginStatus', true);
                    this.$emit('favoriteHandle', true);

                    if (that.clickType == 'favorite') {
                      that.appendFavorites(attrArr[0], attrArr[1], attrArr[2]);
                    } else if (that.clickType == 'addCart') {
                      that.quickPurchase(attrArr[1], attrArr[2]);
                    }
                  }
                }
              }
            } else {
              let res = await uni.showModal({
                title: 'appid有误',
                content: '授权失败'
              });
            }
          }
        } else {
          tip.plainText('您可以再次授权');
        }
      } catch (err) {
      }
    },

    // 商品详情信息
    getGoodsDetail: async function(goodsId) {
      let that = this;
      that.addCartSuccess = false;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
	  if (!goodsId) {
	    uni.redirectTo({
	      url: '/pages/util/pageNotFound'
	    });
	    return false
	  }
      const json = await api.goodsDetail(
        {
          query: {
            merchant_id: merchantInfo.cloudMerchantId,
            store_id: merchantInfo.cloudMerchantStoreId
          }
        },
        goodsId
      );

      if (json.code === 1000) {
        let data = json.data;
        that.itemName = data.itemName;
        that.itemCode = data.itemCode;
        that.price = data.price;

        let valueArr = [];
        for (let z = 0; z < data.skus.length; z++) {
          if (valueArr.indexOf(data.skus[z].skuProperties[0].valueId) == -1) {
            valueArr.push(data.skus[z].skuProperties[0].valueId);
          }
        }

        // detail  商品详情信息
        that.detail = data;
        //  isFront 1-- 颜色 0-- 尺码
        // 库存不为0的数据  qtyNotZero
        const skus = data.skus;
        for (var i = 0; i < skus.length; i++) {
          if (skus[i].skuProperties[0].valueId == parseInt(this.valueId)) {
            that.colorName = skus[i].skuProperties[0].valueName;
            that.markingPrice = skus[i].markingPrice;
            that.skuImageUrl = skus[i].skuImageUrl;
          }

          let skuProperties = skus[i].skuProperties;
          let tmpKey = '';
          let tmpFront = '';
          let flag = skus[i].qty;
          // 过滤掉0库存,对有库存的遍历
          for (var j = 0; j < skuProperties.length; j++) {
            tmpKey += skuProperties[j].valueName;
          }
          this.productList[tmpKey] = skus[i];
        }

        let tempAttribute = this.productList;
        let tempSizeList = [];
        Object.keys(tempAttribute).forEach(item => {
          if (item.indexOf(that.colorName) !== -1) {
            tempSizeList.push(tempAttribute[item]);
          }
        });
        that.colorSizeList = tempSizeList;

        that.showSizeList = true;

        this.$emit('showFadeInUp', false);

        //策略价
        if (that.price == that.markingPrice) {
          let favorite = { itemId: data.itemId, valueId: this.valueId };
          util.getItemPriceRules(favorite, merchantInfo).then(val => {
            if (Number(val) > Number(0)) {
              that.price = val;
            }
          });
        }
      } else {
        tip.plainText('请重试');
      }
    },

    addShoppingCart: async function() {
      let that = this;
      let cart_key = uni.getStorageSync(CART_KEY) || null;
      if (cart_key == null || cart_key == '') {
        that.initCart();
        // that.doTakeCart();
      } else {
        //加入购物车
        that.initCart();
        let cart_key = uni.getStorageSync(CART_KEY) || null;
        if (cart_key != null && cart_key != '') {
          this.doTakeCart();
        }
      }
    },

    //加入购物车
    doTakeCart: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
		const accountInfo = uni.getAccountInfoSync()
		that.$commonFunction.getCartList().then((res) => {
		}).catch((err) => {
			uni.setStorageSync(CART_KEY, null);
			that.initCart();
		});

      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      const json = await api.addCart(
        {
          method: 'POST',
          header: { jwt: jwt },
          query: {
            itemCode: that.addCartItemCode,
            itemName: that.itemName,
            qty: 1,
            skuCode: that.addCartSkuCode,
            skuId: that.addCartSkuId
          }
        },
        that.cartKey + '/item'
      );
      if (json.code === 1000) {
        //显示加购成功信息框
        that.addCartSuccess = true;
        setTimeout(() => {
          this.addCartSuccess = false;
        }, 2000);
        that.getCartList(jwt, that.cartKey);
      } else {
        this.initCart();
        if (json.msg) {
          if (json.code === -1002) {
            let itemNum = json.msg;
            let item = itemNum.substr(3, 6);
            tip.plainText(item);
          }
          this.onGotUserInfoToRegister();
        } else {
          tip.plainText('无法加入购物车');
        }
        this.$emit('loginStatus', false);
      }
    },

    //获取购物车商品列表
    getCartList: async function(jwt, cart_key) {
      let that = this;
      // let cart_key = uni.getStorageSync(CART_KEY);
      // let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      try {
        if (jwt && cart_key !== null) {
			that.$commonFunction.getCartList().then((res) => {
			  // 购物车列表数据
			  if (res && res.items !== null) {
			    let cartItems = res.items;
			    let number = res.availableTotalQty || 0;
			    this.$emit('cartNumStatus', number);
			  }
			}).catch((err) => {
			});
        }
      } catch (err) {
      }
    },

    // 创建购物车获取cart_key
    initCart: async function() {
      let that = this;
      let cart_key = uni.getStorageSync(CART_KEY) || null;
      if (cart_key == null || cart_key == '') {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let cart_key = '';
        let res = await api.checkCart({
          method: 'POST',
          header: { jwt: customerInfo.jwt },
          query: {
            customerId: customerInfo.customerId,
            merchantId: merchantInfo.cloudMerchantId,
            orderSource: 'wxapp',
            storeId: merchantInfo.cloudMerchantStoreId
          }
        });
        if (res.code === 1000) {
          cart_key = res.data;
          that.cartKey = cart_key;
          uni.setStorageSync(CART_KEY, cart_key);
          this.doTakeCart();
        } else {
          let cartRes = await api.initCart({
            method: 'POST',
            header: { jwt: customerInfo.jwt },
            query: {
              customerId: customerInfo.customerId,
              merchantId: merchantInfo.cloudMerchantId,
              orderSource: 'wxapp',
              storeId: merchantInfo.cloudMerchantStoreId
            }
          });
          cart_key = cartRes.data.cartKey;
          that.cartKey = cart_key;
          uni.setStorageSync(CART_KEY, cart_key);
          this.doTakeCart();
        }
      }
    },

    hidePicker() {
      this.showSizeList = false;
      // this.$emit('showFadeInUp', true)
    },

    /**
     * @param {Object} itemId
     * @param {Object} valueId
     * @param {Object} merchantInfo
     *  多条件查询商品收藏信息 favoritesId:-1 代表未收藏
     */
    inquireFavorites: async function(itemId, valueId) {
      let that = this;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      //获取商户信息
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
      if (merchantInfo && jwt) {
        const favoritesInfo = await api.inquireFavorites({
          header: {
            jwt: jwt
          },
          query: {
            item_id: itemId,
            merchant_id: merchantInfo.cloudMerchantId,
            store_id: merchantInfo.cloudMerchantStoreId,
            value_id: valueId
          }
        });
        if (favoritesInfo.code == 1000) {
          let favorites = favoritesInfo.data;
          let favoritesId = favorites.favoritesId;
          if (favoritesId == -1) {
            that.appendFavorites(that.frontCode, that.itemId, that.valueId);
          } else {
            return;
          }
        }
      }
    },

    getMyBackground: async function(merchant_id, config_scope_id) {
      let that = this;
      const json = await api.getStoreInfo({
        method: 'GET',
        query: {
          config_client_id: 'efcloud',
          config_path: 'store/information/account_background',
          config_scope: 'Store',
          config_scope_id: config_scope_id,
          merchant_id: merchant_id
        }
      });
      if (json.code === 1000) {
        uni.setStorageSync('myBackground', json.data.value);
      }
    },
  }
};
</script>

<style lang="less" scoped>
/* 尺码弹框 */
.topSizeList {
  position: fixed;
  bottom: 110rpx;
  left: 0;
  z-index: 10;
  height: 610rpx;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid #ddd;
}
.topSizeList .bg {
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 10;
}
.topSizeList picker-view-column view {
  line-height: 100rpx;
  text-align: center;
}
.topSizeList .cascade_header {
  margin: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
  width: auto;
  background-color: #fff;
}
.topSizeList .sizeBox {
  position: relative;
  z-index: 12;
}
.quxiao,
.queren {
  line-height: 80rpx;
}

.quxiao {
  color: #939393;
}

/* 加购弹框 */
.topBox {
  border: 1px solid #e7e7e7;
  background-color: #fff;
  padding: 60rpx;
  position: fixed;
  top: 30%;
  left: 2.9%;
  width: 77.8%;
}
.topBox .gImg {
  width: 236rpx;
  height: 354rpx;
  margin-right: 60rpx;
}
.topBox .gImg image {
  width: 100%;
  height: 100%;
}
.topBox .gInfo {
  padding-top: 20rpx;
}
.topBox .gNmae {
  margin-bottom: 10rpx;
}
.topBox .gColor {
  margin: 60rpx 0 10rpx 0;
}
.topBox .gContent {
  display: flex;
  margin-bottom: 60rpx;
}
.topBox .icon-bag-o {
  background-color: #444;
  color: #fff;
  padding: 10px 20rpx;
  text-align: center;
  font-size: 28rpx;
}
.topBox .icon-bag-o:before {
  content: '';
}
.topBox .icon-bag-o:after {
  content: '\e603';
}
.topBox .icon-cuowu1 {
  position: absolute;
  right: 16rpx;
  top: 16rpx;
  font-size: 64rpx;
  color: #999;
}

.goodsTag {
  color: #ff571a !important;
  font-size: 24rpx;
  margin-right: 14rpx;
}
</style>
